package com.unit.test.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.unit.test.domain.Member;
import com.unit.test.enumeration.Sex;

public class MemberServiceImpl {
	
	
	JdbcTemplate template;
	
	public void setDataSource(DataSource dataSource) {
		template = new JdbcTemplate(dataSource);
	}
	

	public int insertMember(Member member) {
		String sql = "insert into member(id,member_name,sex,createTime,birthday,high,age,flag) "
				+ "value(?,?,?,?,?,?,?,?)"; 		
		int effect = template.update(sql, new PreparedStatementSetter() {			
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setObject(1, member.getId());
				ps.setObject(2, member.getMemberName());
				ps.setObject(3, member.getSex().getIndex());
				ps.setObject(4, member.getCreateTime());
				ps.setObject(5, member.getBirthday());
				ps.setObject(6, member.getHigh());
				ps.setObject(7, member.getAge());
				ps.setObject(8, member.getFlag());
			}
		});		
		return effect;
	}
	
	
	public Member queryMember(long id) {
		String sql = "select * from member where id = "+id ;
		return template.query(sql, new ResultSetExtractor<Member>() {

			@Override
			public Member extractData(ResultSet rs) throws SQLException, DataAccessException {
				Member member = new Member();
				while(rs.next()){
					member.setId(rs.getLong("id"));
					member.setAge(rs.getInt("age"));
					member.setBirthday(rs.getTimestamp("birthday").toLocalDateTime().toLocalDate());
					member.setCreateTime(rs.getTimestamp("createTime").toLocalDateTime());
					member.setFlag(rs.getBoolean("flag"));
					member.setHigh(rs.getBigDecimal("high"));
					member.setMemberName(rs.getString("member_name"));
					member.setSex(Sex.findIndex(rs.getInt("sex")));					
				}
				return member;
			}
			
		});
	}

}
